package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.util.Md5Utils;
import com.ndp.ec.core.model.template.ElementPackage;
import com.ndp.ec.core.model.template.TemplateZip;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.model.business.vo.ectemplate.EcTemplateFilterParam;
import com.ndp.fb.rdb.api.*;
import com.ndp.fb.rdb.model.*;
import com.ndp.fb.rdb.model.ectemplate.*;
import com.ndp.fb.storage.StorageService;
import com.ndp.fb.util.FileUtil;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.TemplateService;
import com.ndp.fb.walle.model.vo.ectemplate.result.EcTemplateList;
import com.ndp.fb.walle.util.FileUploadUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * Created by evan on 2016/6/27.
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Reference
    EcTemplateRdbService ecTemplateRdbService;

    @Autowired
    StorageService storageService;

    @Reference
    EcMaterielCategoryRdbService ecMaterielCategoryRdbService;

    @Reference
    EcElementCategoryRdbService ecElementCategoryRdbService;

    @Reference
    EcTemplateElementRdbService ecTemplateElementRdbService;

    @Reference
    EcElementStyleRdbService ecElementStyleRdbService;

    @Reference
    EcColorTypeRdbService ecColorTypeRdbService;

    @Reference
    EcFontRdbService ecFontRdbService;

    @Reference
    EcProductLogoRdbService ecProductLogoRdbService;

    @Reference
    private EcTemplateElementStyleRdbService ecTemplateElementStyleRdbService ;

    @Reference
    EcElementStyleColorTypeRdbService ecElementStyleColorTypeRdbService;


    @Override
    public Pager<EcTemplateList> getTemplateWithPager(Long orgId, String name, int order, List<Long> templateStatus, List<EcTemplateFilterParam> filterList, Integer firstResult, Integer sizeNo) {
        Pager<EcTemplateList> pager = new Pager<>();
        List<EcTemplateList> list = new ArrayList<>();
        Pager<EcTemplate> ecTemplatePager = ecTemplateRdbService.getTemplateWithPager(orgId, name, order, templateStatus, filterList, firstResult, sizeNo);
        pager.setTotalSize(ecTemplatePager.getTotalSize());
        if(ListUtil.isEmpty(ecTemplatePager.getResultList()))
            return pager;
        List<Long> ecTemplateIds = ecTemplatePager.getResultList().stream().map(EcTemplate::getId).collect(toList());
        List<EcTemplateGroupCnt> groupCnts = ecTemplateRdbService.getTemplateGroupCnt(ecTemplateIds);
        List<EcTemplateGroupCnt> brandCnts = ecProductLogoRdbService.getProductByTemplateId(ecTemplateIds);
        EcTemplateList ecTemplateRes;
        for(EcTemplate obj : ecTemplatePager.getResultList()) {
            ecTemplateRes = new EcTemplateList();
            BeanUtils.copyProperties(obj, ecTemplateRes);
            for(EcTemplateGroupCnt cnt : groupCnts) {
                if(obj.getId().equals(cnt.getTemplateId()))
                    ecTemplateRes.setGroupCnt(cnt.getCnt());
            }
            for(EcTemplateGroupCnt cnt : brandCnts) {
                if(obj.getId().equals(cnt.getTemplateId()))
                    ecTemplateRes.setBrandCnt(cnt.getCnt());
            }
            list.add(ecTemplateRes);
        }
        pager.setResultList(list);
        return pager;
    }

    @Override
    public void del(Long id) {
        //一、物理删除多对多关系表   逻辑删除template
        ecTemplateRdbService.delLogic(id);
    }

    @Override
    public EcTemplate updateStatus(Long id, int active) {
        return ecTemplateRdbService.updateStatus(id, active);
    }

    @Override
    public void parse(User user, String folder) throws Exception {
        List<EcMaterielCategory> catalogs =  ecMaterielCategoryRdbService.findAllCN();
        List<EcElementStyle> ecElementStyles = ecElementStyleRdbService.findAll();
        List<EcColorType> ecColorTypes = ecColorTypeRdbService.findAll();
        Map<String, Long> catalogMap = catalogs.stream().filter(i -> StringUtil.isNotEmpty(i.getCategoryType())).collect(Collectors.toMap(EcMaterielCategory::getCategoryType, EcMaterielCategory::getId));
        Map<String, Long> ecElementStyleMap = ecElementStyles.stream().filter(i -> StringUtil.isNotEmpty(i.getCode())).collect(Collectors.toMap(EcElementStyle::getCode, EcElementStyle::getId));
        Map<String, Long> ecColorTypeMap = ecColorTypes.stream().filter(i -> StringUtil.isNotEmpty(i.getName())).collect(Collectors.toMap(EcColorType::getName, EcColorType::getId));
        //一、对文件夹 进行逐一解析，模板优先
        Long templateId = null;
        boolean newTemplate = true;
        File file = new File(folder);
        File[] files = file.listFiles();
        //json文件排在前面了
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return 1;
                if (o1.isFile() && o2.isDirectory())
                    return -1;
                return o2.getName().compareTo(o1.getName()) > 0 ? -1 : 1;
            }
        });
        String templateContext = "";
        for(File f : files){
            if(f.isFile()){
                if(f.getName().toUpperCase().endsWith(".JSON")) {
                    templateContext = FileUtils.readFileToString(f, "gbk");
                } else {
                    String templateName = FileUploadUtils.getFileNameNoEx(f.getName()).toUpperCase();
                    /**
                     * 对模板名字解析 CA_A0101_bg99_0002
                     * 第一位 适用创意类型 轮播还是链接广告
                     * 第二位 模板编码A0101  首字母A: 左右结构 B: 上下结构 C： 全局结构
                     * 第三位 背景处理方式
                     * 第四位 颜色类型
                     */
                    String[] templateNameArr = templateName.split(CommonConstants.SYMBOL_UNDERLINE);

                    //该模板存在过，覆盖template_img   template_context
                    EcTemplate ecTemplate = ecTemplateRdbService.findByName(templateName, user.getOrgId());
                    List<EcTemplateCategory> ecTemplateCategories = new ArrayList<>();

                    if(ecTemplate == null) {
                        templateId = saveTemplate(user, f, templateName, templateNameArr, templateContext);
                    } else {
                        newTemplate = false;
                        templateId = ecTemplate.getId();
                        String templateImgUrl;

                        logger.info("update template to s3 templateImgUrl>>>" + f.getName());
                        try{
                            templateImgUrl = storageService.storeTemplateAsPublic(templateId, f);
                        } catch (IOException e) {
                            //模板png存s3异常再存一次
                            templateImgUrl = storageService.storeTemplateAsPublic(templateId, f);
                        }
                        ecTemplateRdbService.cover(templateId, templateImgUrl, templateContext);

                        //如果删除 难么就保存
                        if (ecTemplate.getIsDelete() != null && ecTemplate.getIsDelete() == 1){
                            ecTemplateRdbService.updateDeleteStatus(0, templateId);
                        }
                    }


                    //补全所有的分类
                    EcTemplateCategory temp1 = new EcTemplateCategory();  //创意类型
                    temp1.setTemplateId(templateId);
                    temp1.setCategoryId(catalogMap.get(templateNameArr[0]));
                    ecTemplateCategories.add(temp1);
                    EcTemplateCategory temp2 = new EcTemplateCategory();   //模板结构
                    temp2.setTemplateId(templateId);
                    temp2.setCategoryId(catalogMap.get(templateNameArr[0] + templateNameArr[1].substring(0, 1)));
                    ecTemplateCategories.add(temp2);

                    logger.info("------------------------");
                    logger.info("save ecTemplateCategories>>>>>");
                    logger.info(">>" + JSON.toJSONString(ecTemplateCategories));
                    logger.info("------------------------");
                    ecTemplateRdbService.batchSaveTemplateCatalog(ecTemplateCategories);
                }
            }
        }

        //二、解析zip包中文件夹  包括元素 font logo
        List<EcTemplateElement> ecTemplateElementList = new ArrayList<>();
        if(templateId != null && templateId != 0L) {
            for(File f : file.listFiles()){
                if(f.isDirectory()){
                    String xx = f.getName();
                    switch (TemplateZip.getStatus(f.getName())) {
                        case ELEMENT:
                            //这套模板zip包有几组样式 F01 S01
                            List templateElementStyleGroup = new ArrayList<>();
                            //解析元素
                            File elementsFile = new File(f.getAbsolutePath());
                            for(File eachElementFolder : elementsFile.listFiles()) {
                                if(f.isDirectory()) {
                                    File eachElementFolderInColor = new File(eachElementFolder.getAbsolutePath());
                                    switch (ElementPackage.getStatus(eachElementFolder.getName())) {
                                        case BLACK:
                                        case GOLD:
                                        case GRAY:
                                        case RED:
                                        case WHITE:
                                            parseElement(templateId, user, ecTemplateElementList, eachElementFolderInColor, ecElementStyleMap, ecColorTypeMap, templateElementStyleGroup);
                                            break;
                                    }
                                }
                            }
                            break;
                        case FONT:
                            logger.info("是字体" + xx);
                            parseFont(templateId, newTemplate, user, folder, f);
                            break;
                        case LOGO:
                            logger.info("是logo" + xx);
                            break;
                    }


                }
            }
        }
        //批量保存元素
        if(ListUtil.isNotEmpty(ecTemplateElementList))
            ecTemplateElementRdbService.batchSave(ecTemplateElementList);

    }

    /**
     * 字体文件夹解析
     * @param user
     * @param folder
     * @param f
     * @throws IOException
     */
    private void parseFont(Long templateId, boolean newTemplate, User user, String folder, File f) throws Exception {
        File fontsFile = new File(f.getAbsolutePath());
        for(File eachFontFile : fontsFile.listFiles()) {
            if (eachFontFile.isFile() && ("ttf".equals(FileUploadUtils.getFileNameEx(eachFontFile.getName().toLowerCase()))
                    || "ttc".equals(FileUploadUtils.getFileNameEx(eachFontFile.getName().toLowerCase())))) {

                String fontFileMd5 = Md5Utils.md5AsBase64(eachFontFile);
                Font font = Font.createFont(Font.TRUETYPE_FONT, eachFontFile);
                String fontName = font.getFamily();
                String fontWeight = null;
                if (font.getName().contains("Regular")) {
                    fontWeight = "normal";
                } else {
                    fontWeight = "bold";
                }

                EcFont ecFont = ecFontRdbService.findEcFontByFontNameAndfontWeight(user.getOrgId(), fontName, fontWeight);
                if(ecFont == null) {
                    ecFont = new EcFont();

                    String extension = FileUtil.getExtension(eachFontFile.getName());
                    String baseFileName =  FileUtil.getFileBaseName(eachFontFile.getName()).replaceAll("\\W","_");
                    String fileName = baseFileName + "." + extension;

                    String storePath = storageService.storeFontAsPublic(null, eachFontFile, fileName);

                    ecFont.setFontName(font.getFamily());
                    ecFont.setFontWeight(fontWeight);
                    ecFont.setOrgId(user.getOrgId());
                    ecFont.setMd5(fontFileMd5);

                    ecFont.setStorePath(storePath);

                    ecFont.setCreateTime(System.currentTimeMillis());
                    ecFont.setFontUrl(storageService.getHttpUrl(storePath));
                    ecFont.setUserId(user.getTicket());
                    ecFont.setPreviewImg(storageService.storeFontAsPublicResultHttp(null, buildPreviewImg(folder, eachFontFile), null));
                    Long fontId = ecFontRdbService.save(ecFont);
                    EcTemplateFont ecTemplateFont = new EcTemplateFont();
                    ecTemplateFont.setFontId(fontId);
                    ecTemplateFont.setTemplateId(templateId);
                    ecTemplateRdbService.saveTemplateFont(ecTemplateFont);

                } else if (newTemplate) {
                    EcTemplateFont ecTemplateFont = new EcTemplateFont();
                    ecTemplateFont.setFontId(ecFont.getId());
                    ecTemplateFont.setTemplateId(templateId);
                    ecTemplateRdbService.saveTemplateFont(ecTemplateFont);
                }
            }
        }
    }

    /**
     * 元素包解析
     * @param user
     * @param ecTemplateElementList
     * @param eachElementFolderInColor
     * @param ecElementStypeMap
     * @param ecColorTypeMap
     * @param templateElementStyleGroup
     * @throws IOException
     */
    @Override
    public void parseElement(Long templateId, User user, List<EcTemplateElement> ecTemplateElementList, File eachElementFolderInColor,
                              Map<String, Long> ecElementStypeMap, Map<String, Long>  ecColorTypeMap, List templateElementStyleGroup) throws Exception {
        EcTemplateElement ecTemplateElement;
        File[] files = eachElementFolderInColor.listFiles();
        //按文件名升序排了
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return 1;
                if (o1.isFile() && o2.isDirectory())
                    return -1;
                return o2.getName().compareTo(o1.getName()) > 0 ? -1 : 1;
            }
        });
        /**
         * 先解析每个颜色包里的json map临时存储context内容
         */
        Map<String, String> elementContextMap = new HashMap<>();
        /**
         * 先解析每个颜色包里的预览图 map临时存储内容
         */
        Map<String, String> elementShowImgMap = new HashMap<>();
        for(File eachElement : files) {
            if(eachElement.getName().toUpperCase().endsWith(".JSON")) {
                JSONArray contexts = JSON.parseArray(FileUtils.readFileToString(eachElement, "gbk"));
                if(contexts != null && contexts.size() > 0) {
                    for(int m = 0; m < contexts.size(); m++) {
                        JSONObject obj = (JSONObject) contexts.get(m);
                        elementContextMap.put(obj.get("code").toString().toUpperCase(), obj.toJSONString());
                    }
                }
            } else if(eachElement.getName().startsWith("00000_")) {
                String elementShowName = FileUploadUtils.getFileNameNoEx(eachElement.getName().replaceAll("00000_", ""));
                String elementShowImgPath;
                logger.info("update element to s3 elementName>>>" + eachElement.getName());
                try {
                    elementShowImgPath = storageService.storeElementAsPublic(elementShowName, eachElement, eachElement.getName());
                } catch (IOException e) {
                    elementShowImgPath = storageService.storeElementAsPublic(elementShowName, eachElement, eachElement.getName());
                }
                elementShowImgMap.put(elementShowName, elementShowImgPath);
            } else {
                //非预览图 该元素存在过，覆盖element_img   element_context  element_preview
                String elementName = FileUploadUtils.getFileNameNoEx(eachElement.getName());
                EcTemplateElement elementExist = ecTemplateElementRdbService.findByName(elementName, user.getOrgId());
                String imgPath;
                logger.info("update element to s3 elementName>>>" + elementName);
                try {
                    imgPath = storageService.storeElementAsPublic(elementName, eachElement, eachElement.getName());
                } catch (IOException e ){
                    imgPath = storageService.storeElementAsPublic(elementName, eachElement, eachElement.getName());
                }
                if(elementExist == null) {
                    String[] elementNameArr = elementName.split(CommonConstants.SYMBOL_UNDERLINE);
                    if (!verifyName(elementNameArr, ecColorTypeMap)){
                        continue;
                    }

                    if(templateId != null && templateId != 0L)
                    {
                        //模板中有几组样式
                        int elementStyleGroup = Integer.parseInt(elementNameArr[1].substring(1, 3));
                        EcTemplateElementStyle ecTemplateElementStyle1 = ecTemplateElementStyleRdbService.findByTemplateIdAndElementStyleGroupId(templateId, elementStyleGroup);
                        if(!templateElementStyleGroup.contains(elementStyleGroup)  && ecTemplateElementStyle1 == null) {
                            EcTemplateElementStyle ecTemplateElementStyle = new EcTemplateElementStyle();
                            ecTemplateElementStyle.setTemplateId(templateId);
                            ecTemplateElementStyle.setElementStyleGroupId(elementStyleGroup);
                            ecTemplateElementStyleRdbService.save(ecTemplateElementStyle);
                            templateElementStyleGroup.add(elementStyleGroup);
                        }
                    }

                    ecTemplateElement = new EcTemplateElement();
                    ecTemplateElement.setElementName(elementName);
                    ecTemplateElement.setIsDelete(0);
                    ecTemplateElement.setCreateTime(new Date().getTime());
                    ecTemplateElement.setOrgId(user.getOrgId());
                    ecTemplateElement.setUserId(user.getTicket());
                    ecTemplateElement.setElementColorTypeId(ecColorTypeMap.get(elementNameArr[2].toLowerCase()));
                    /**
                     * 解析到样式组是否存在
                     * 1、存在直接保存
                     * 2、不存在需要先创建样式ec_element_style
                     */
                    String styleCode = elementNameArr[1].toUpperCase();
                    boolean isMajor = "F".equals(elementNameArr[1].substring(0, 1).toUpperCase());
                    if(ecElementStypeMap.containsKey(styleCode)) {
                        ecTemplateElement.setElementStyleId(ecElementStypeMap.get(styleCode));
                    } else {
                        EcElementStyle ecElementStyle = new EcElementStyle();
                        ecElementStyle.setCode(styleCode);
                        ecElementStyle.setStyleGroup(Integer.parseInt(styleCode.substring(1, styleCode.length())));
                        ecElementStyle.setEnName(isMajor ? (CommonConstants.TEMPLATE_STYLE_F_EN + elementNameArr[1]) : (CommonConstants.TEMPLATE_STYLE_S_EN + elementNameArr[1]));
                        ecElementStyle.setName(isMajor ? (CommonConstants.TEMPLATE_STYLE_F + elementNameArr[1]) : (CommonConstants.TEMPLATE_STYLE_S + elementNameArr[1]));
                        ecElementStyle.setSort(isMajor ? 1 : 2);
                        Long elementStyleId = ecElementStyleRdbService.save(ecElementStyle);
                        EcElementStyleColorType ecElementStyleColorType = new EcElementStyleColorType();
                        ecElementStyleColorType.setElementColorTypeId(1L);
                        ecElementStyleColorType.setElementStyleId(elementStyleId.intValue());
                        ecElementStyleColorTypeRdbService.save(ecElementStyleColorType);
                        ecElementStypeMap.put(styleCode, elementStyleId);
                        ecTemplateElement.setElementStyleId(elementStyleId);
                    }
                    ecTemplateElement.setMajor(isMajor);
                    ecTemplateElement.setParentCode(elementNameArr[0].substring(0, 3).toUpperCase());
                    ecTemplateElement.setElementCode(elementName.toUpperCase());
                    ecTemplateElement.setElementImg(imgPath);
                    ecTemplateElement.setElementPreview(elementShowImgMap.get(elementName));
                    if(StringUtil.isNotEmpty(elementContextMap.get(elementName)))
                        ecTemplateElement.setElementContext(elementContextMap.get(elementName).replaceAll("#" + elementName, imgPath));
                    ecTemplateElementList.add(ecTemplateElement);
                } else {
                    String context = elementContextMap.get(elementName);
                    if (!StringUtils.isEmpty(context)){
                        context = context.replaceAll("#" + elementName, imgPath);
                    }
                    ecTemplateElementRdbService.cover(elementExist.getId(), imgPath, elementShowImgMap.get(elementName), context);
                }
            }
        }
    }

    private boolean verifyName(String[] elementNameArr, Map<String, Long> ecColorTypeMap){
        int nameLength = elementNameArr.length;
        //a0101p_f01_gold.png
        if (nameLength < 3 ){
            //还需要丰富名称的校验
            //todo 应该要抛出文件名错误的信息
            return false;
        }

        // 元素层级只能用 F、S来表示
        String level = elementNameArr[1];
        if (level.length() != 3){
            return false;
        }
        if (!level.startsWith("F") && !level.startsWith("S")){
            return false;
        }
        //一个元素下可能有多个样式 01~99
        try {
            Integer styleGroup =  Integer.valueOf(level.substring(1,2));
        } catch (Exception e){
            logger.error(e.getMessage(), e);
            return false;
        }

        Long colorType = ecColorTypeMap.get(elementNameArr[2].toLowerCase());
        if (null == colorType){
            //todo 应该要抛出文件名错误的信息-颜色错误信息
            return false;
        }
        return true;
    }

    private Long saveTemplate(User user, File f, String templateName, String[] templateNameArr, String templateContext) throws IOException {
        EcTemplate ecTemplate = new EcTemplate();
        ecTemplate.setOrgId(user.getOrgId());
        ecTemplate.setUserId(user.getTicket());
        ecTemplate.setIsDelete(0);
        ecTemplate.setActive(0);
        ecTemplate.setTemplateName(templateName);
        ecTemplate.setTemplateCode(templateNameArr[1]);
        ecTemplate.setTemplateBgType(templateNameArr[4]);
        //CA_A0106_600_600_BG99_BK0004
        //CA_A0106_600_600_BG01_30002_BK0004
        if(templateNameArr.length >= 6)
            ecTemplate.setTemplateBgStyle(templateNameArr[5]);
        if(templateNameArr.length >= 7)
            ecTemplate.setTemplateBk(templateNameArr[6]);
        ecTemplate.setWidth(Integer.parseInt(templateNameArr[2]));
        ecTemplate.setHeight(Integer.parseInt(templateNameArr[3]));
        ecTemplate.setTemplateContext(templateContext);
        ecTemplate.setCreateTime(new Date().getTime());
        Long templateId = ecTemplateRdbService.save(ecTemplate);
        //生成上传的文件s3地址
        String httpUrl;
        try{
            httpUrl = storageService.storeTemplateAsPublic(templateId, f);
        } catch (IOException e) {
            //模板png存s3异常再存一次
            httpUrl = storageService.storeTemplateAsPublic(templateId, f);
        }
        ecTemplateRdbService.updateTemplateImg(templateId, httpUrl);
        return templateId;
    }

    /**
     * 构建字体预览图
     * @param filePath
     * @return
     */
    public File buildPreviewImg(String filePath, File fontFile) {
        String fileName = System.currentTimeMillis() + ".jpg";
        String path = filePath + "/" + fileName;
        File file = new File(path);

        BufferedImage bi = new BufferedImage(700, 70, BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, 700, 70);
        //文本抗锯齿提示值——文本呈现需要使用字体资源中的信息，这些信息指定了每个点大小是否适合应用
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //字体小数规格提示值——用子像素精确度定位字符字形。
        g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        g2.setFont(loadFont(fontFile, 24));
        g2.setPaint(Color.BLACK);

        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2.drawString("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, 30);
        g2.drawString("123456789.:,;'(!?)+-*/=", 0, 60);

        try {
            ImageIO.write(bi, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public  Font loadFont(File file, float fontSize)
    {
        try
        {
            FileInputStream aixing = new FileInputStream(file);
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
            Font dynamicFontPt = dynamicFont.deriveFont(fontSize);
            Font dynamicFontBold = dynamicFontPt.deriveFont(Font.PLAIN);
            aixing.close();
            return dynamicFontBold;
        }
        catch(Exception e)
        {
            logger.error("加载字体异常：", e);
            return new java.awt.Font("宋体", Font.PLAIN, 24);
        }
    }

}
